from django.shortcuts import render
from app01.models import Yser
from rest_framework.views import APIView
from rest_framework.response import Response
import uuid
from qiniu import Auth,put_file,etag

class Sgjr(APIView):
    def post(self,request):
        data = request.data
        print(data)
        pic = data["pic"]
        uuid_str = str(uuid.uuid4())
        pic_name = uuid_str + pic.name

        try:
            with open(pic_name, "wb") as f:
                for i in pic.chunks():
                    f.write(i)

            AK = 'J-xrdLFGyNeaKwM6sNRv7jD1brr4u3IxL87fhrgj'
            SK = 'fjj-P5cxxSRE71JcAs7Tq4YE6SzdZsFvuQyMYSOK'
            q = Auth(AK, SK)
            bucket_name = "dxcfvbn123"
            key = pic_name
            token = q.upload_token(bucket_name, key, 3600)
            localfile = './%s' % pic_name
            ret, info = put_file(token, key, localfile)

            url = "http://q5vmy6kon.bkt.clouddn.com/" + pic_name

            Yser.objects.create(name=data["name"], age=data["age"],
                                phone=data["phone"], email=data["email"])
            res_data = {
                "code": 200,
                "msg": "成功",
                "url": url
            }
            return Response(res_data)
        except Exception as e:
            # raise e
            res_data = {
                "code": 500,
                "msg": "失败"
            }
            return Response(res_data)
